<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Refresh, Check, Close } from '@element-plus/icons-vue'
import request from '@/utils/request'

// Tabs
const route = useRoute()
type Tab = 'bank' | 'recharge' | 'withdraw' | 'settings'
const active = ref<Tab>((route.query.tab as any) || 'bank')
// ========== 출금 심사 ==========
const withdrawList = ref<any[]>([])
const withdrawLoading = ref(false)
const withdrawStatusFilter = ref<string>('') // 空字符串表示显示所有状态

async function fetchWithdrawals(status?: string) {
  withdrawLoading.value = true
  try {
    const { data } = await request.get('/api/admin/withdrawals', {
      params: status ? { status } : {},
    })
    withdrawList.value = data
  } finally {
    withdrawLoading.value = false
  }
}

async function approveWithdraw(row: any) {
  await request.put(`/api/admin/withdrawals/${row.id}/approve`)
  ElMessage.success('승인됨')
  await fetchWithdrawals(withdrawStatusFilter.value || undefined)
}

async function rejectWithdraw(row: any) {
  await ElMessageBox.confirm('이 출금을 거부하시겠습니까?', '알림', { type: 'warning' })
  await request.put(`/api/admin/withdrawals/${row.id}/reject`, { remark: '관리자 거부' })
  ElMessage.success('거부됨')
  await fetchWithdrawals(withdrawStatusFilter.value || undefined)
}

// 编辑银行信息
const bankInfoDialog = ref(false)
const bankInfoForm = reactive({
  id: '',
  bankName: '',
  accountName: '',
  accountNumber: '',
  accountId: ''
})

function editBankInfo(row: any) {
  bankInfoForm.id = row.id
  bankInfoForm.bankName = row.payoutBankName || ''
  bankInfoForm.accountName = row.payoutAccountName || ''
  bankInfoForm.accountNumber = row.payoutAccountNumber || ''
  bankInfoForm.accountId = row.payoutAccountId || ''
  bankInfoDialog.value = true
}

async function saveBankInfo() {
  if (!bankInfoForm.bankName || !bankInfoForm.accountName || !bankInfoForm.accountNumber || !bankInfoForm.accountId) {
    ElMessage.error('완전한 은행 정보를 입력하세요')
    return
  }

  try {
    await request.put(`/api/admin/withdrawals/${bankInfoForm.id}/bank-info`, {
      bankName: bankInfoForm.bankName,
      accountName: bankInfoForm.accountName,
      accountNumber: bankInfoForm.accountNumber,
      accountId: bankInfoForm.accountId
    })
    ElMessage.success('은행 정보가 업데이트되었습니다')
    bankInfoDialog.value = false
    await fetchWithdrawals(withdrawStatusFilter.value || undefined)
  } catch (error) {
    ElMessage.error('업데이트 실패')
  }
}

// 获取状态显示文本
function getStatusText(status: string) {
  switch (status) {
    case 'pending': return '대기 중'
    case 'approved': return '승인됨'
    case 'rejected': return '거부됨'
    default: return status
  }
}

// 获取状态标签类型
function getStatusType(status: string) {
  switch (status) {
    case 'pending': return 'warning'
    case 'approved': return 'success'
    case 'rejected': return 'danger'
    default: return 'info'
  }
}

// ========== 출금 설정 ==========
const settings = ref({ rate: 0.01, feePercent: 10, minPoints: 0, banks: [] as string[] })
const banksString = computed({
  get: () => (settings.value.banks || []).join(','),
  set: (v: string) => {
    settings.value.banks = v
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean)
  },
})
async function loadSettings() {
  const { data } = await request.get('/api/admin/settings/withdraw')
  settings.value = data
}
async function saveSettings() {
  // 숫자 타입 정확성 보장
  const settingsData = {
    ...settings.value,
    rate: parseFloat(String(settings.value.rate)) || 0,
    feePercent: parseFloat(String(settings.value.feePercent)) || 0,
    minPoints: parseInt(String(settings.value.minPoints)) || 0
  }
  await request.put('/api/admin/settings/withdraw', settingsData)
  ElMessage.success('저장됨')
}

// 金额/Decimal 安全格式化显示（保留两位小数）
function formatDecimal(val: any): string {
  try {
    if (val === null || val === undefined) return '-'

    // 处理 Prisma.Decimal 对象
    if (val && typeof val === 'object') {
      // 尝试多种方式获取数值
      if (typeof val.toString === 'function') {
        const str = val.toString()
        const n = Number(str)
        if (Number.isFinite(n)) return n.toFixed(2)
      }
      if (typeof val.toNumber === 'function') {
        const n = val.toNumber()
        if (Number.isFinite(n)) return n.toFixed(2)
      }
      if (val.d && Array.isArray(val.d)) {
        // Decimal.js 내부 구조
        const str = String(val)
        const n = Number(str)
        if (Number.isFinite(n)) return n.toFixed(2)
      }
      // 如果是普通对象，返回 JSON 字符串
      return JSON.stringify(val)
    }

    // 处理字符串和数字
    const n = Number(val)
    return Number.isFinite(n) ? n.toFixed(2) : String(val)
  } catch (e) {
    console.warn('formatDecimal error:', e, val)
    return String(val)
  }
}

// ========== 은행 카드 관리 ==========
const bankList = ref<any[]>([])
const bankForm = reactive({
  displayName: '',
  bankName: '',
  accountName: '',
  accountNumber: '',
  note: '',
  qrCodeUrl: '',
  isActive: true,
})
const bankDialog = ref(false)

async function fetchBanks() {
  const { data } = await request.get('/api/admin/bank-accounts')
  bankList.value = data
}
async function onCreateBank() {
  if (!bankForm.displayName && !(bankForm.bankName || bankForm.accountName)) {
    ElMessage.error('최소한 표시명 또는 은행/계좌명을 입력하세요')
    return
  }
  await request.post('/api/admin/bank-accounts', bankForm)
  ElMessage.success('생성됨')
  bankDialog.value = false
  await fetchBanks()
}
async function onToggleBank(row: any) {
  await request.put(`/api/admin/bank-accounts/${row.id}`, { isActive: !row.isActive })
  ElMessage.success('업데이트됨')
  await fetchBanks()
}

// ========== 充值审核 ==========
const rechargeList = ref<any[]>([])
const rechargeLoading = ref(false)
async function fetchRecharges(status?: string) {
  rechargeLoading.value = true
  try {
    const { data } = await request.get('/api/admin/recharges', { params: status ? { status } : {} })
    rechargeList.value = data
  } finally {
    rechargeLoading.value = false
  }
}
async function approveRecharge(row: any) {
  await request.put(`/api/admin/recharges/${row.id}/approve`)
  ElMessage.success('승인됨')
  await fetchRecharges('pending')
}
async function rejectRecharge(row: any) {
  await ElMessageBox.confirm('이 충전을 거부하시겠습니까?', '알림', { type: 'warning' })
  await request.put(`/api/admin/recharges/${row.id}/reject`, { reason: '관리자 거부' })
  ElMessage.success('거부됨')
  await fetchRecharges('pending')
}





onMounted(() => {
  fetchBanks()
  fetchRecharges('pending')
  fetchWithdrawals() // 기본적으로 모든 상태 표시
  loadSettings()
})
</script>

<template>
  <div class="payment-mgmt">
    <h2 class="title">결제 관리</h2>

    <el-tabs v-model="active">
      <!-- 은행 카드 -->
      <el-tab-pane label="은행 카드 관리" name="bank">
        <div class="toolbar">
          <el-button type="primary" :icon="Plus" @click="bankDialog = true">은행 카드 추가</el-button>
          <el-button :icon="Refresh" @click="fetchBanks">새로고침</el-button>
        </div>
        <el-table :data="bankList" stripe>
          <el-table-column prop="displayName" label="표시명" min-width="140" />
          <el-table-column prop="bankName" label="은행" width="120" />
          <el-table-column prop="accountName" label="계좌명" width="140" />
          <el-table-column prop="accountNumber" label="계좌번호" min-width="180" />
          <el-table-column prop="isActive" label="활성화" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isActive ? 'success' : 'info'">{{
                row.isActive ? '예' : '아니오'
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="작업" width="140" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="onToggleBank(row)">{{
                row.isActive ? '비활성화' : '활성화'
              }}</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog v-model="bankDialog" title="은행 카드 추가" width="520px">
          <el-form :model="bankForm" label-width="96px">
            <el-form-item label="표시명"><el-input v-model="bankForm.displayName" /></el-form-item>
            <el-form-item label="은행"><el-input v-model="bankForm.bankName" /></el-form-item>
            <el-form-item label="계좌명"><el-input v-model="bankForm.accountName" /></el-form-item>
            <el-form-item label="계좌번호"><el-input v-model="bankForm.accountNumber" /></el-form-item>
            <el-form-item label="비고"><el-input v-model="bankForm.note" /></el-form-item>
            <el-form-item label="QR코드 URL"><el-input v-model="bankForm.qrCodeUrl" /></el-form-item>
            <el-form-item label="활성화 여부"><el-switch v-model="bankForm.isActive" /></el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="bankDialog = false">취소</el-button>
            <el-button type="primary" @click="onCreateBank">저장</el-button>
          </template>
        </el-dialog>
      </el-tab-pane>

      <!-- 출금 심사 -->
      <el-tab-pane label="출금 심사" name="withdraw">
        <div class="toolbar">
          <el-select v-model="withdrawStatusFilter" placeholder="상태 필터" style="width: 120px; margin-right: 10px" @change="fetchWithdrawals(withdrawStatusFilter || undefined)">
            <el-option label="전체" value="" />
            <el-option label="대기 중" value="pending" />
            <el-option label="승인됨" value="approved" />
            <el-option label="거부됨" value="rejected" />
          </el-select>
          <el-button :icon="Refresh" @click="fetchWithdrawals(withdrawStatusFilter || undefined)">새로고침</el-button>
        </div>
        <el-table :data="withdrawList" v-loading="withdrawLoading" stripe>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="userId" label="사용자" width="80" />
          <el-table-column label="포인트" width="120">
            <template #default="{ row }">{{ String(row.pointsToWithdraw ?? '') }}</template>
          </el-table-column>
          <el-table-column label="예상 입금액(￥)" width="140">
            <template #default="{ row }">{{ formatDecimal(row.amountDecimal) }}</template>
          </el-table-column>
          <el-table-column prop="referenceNo" label="참조 번호" min-width="160" />
          <el-table-column label="수취 정보" min-width="280">
            <template #default="{ row }">
              <div v-if="row.payoutBankName || row.payoutAccountName || row.payoutAccountNumber || row.payoutAccountId">
                <div v-if="row.payoutBankName"><strong>은행:</strong> {{ row.payoutBankName }}</div>
                <div v-if="row.payoutAccountName"><strong>성명:</strong> {{ row.payoutAccountName }}</div>
                <div v-if="row.payoutAccountNumber"><strong>카드번호:</strong> {{ row.payoutAccountNumber }}</div>
                <div v-if="row.payoutAccountId"><strong>신분증:</strong> {{ row.payoutAccountId }}</div>
              </div>
              <span v-else class="text-gray-400">미입력</span>
            </template>
          </el-table-column>
          <el-table-column label="상태" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="작업" width="240" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <template v-if="row.status === 'pending'">
                  <el-button type="success" :icon="Check" size="small" @click="approveWithdraw(row)">승인</el-button>
                  <el-button type="danger" :icon="Close" size="small" @click="rejectWithdraw(row)">거부</el-button>
                </template>
                <span v-else class="processed-status">처리됨</span>
                <el-button type="primary" size="small" @click="editBankInfo(row)">은행 정보 편집</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 은행 정보 편집 대화상자 -->
        <el-dialog v-model="bankInfoDialog" title="은행 정보 편집" width="520px">
          <el-form :model="bankInfoForm" label-width="96px">
            <el-form-item label="은행명" required>
              <el-input v-model="bankInfoForm.bankName" placeholder="은행명을 입력하세요" />
            </el-form-item>
            <el-form-item label="계좌 성명" required>
              <el-input v-model="bankInfoForm.accountName" placeholder="계좌 성명을 입력하세요" />
            </el-form-item>
            <el-form-item label="은행 카드 번호" required>
              <el-input v-model="bankInfoForm.accountNumber" placeholder="은행 카드 번호를 입력하세요" />
            </el-form-item>
            <el-form-item label="신분증 번호" required>
              <el-input v-model="bankInfoForm.accountId" placeholder="신분증 번호를 입력하세요" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="bankInfoDialog = false">취소</el-button>
            <el-button type="primary" @click="saveBankInfo">저장</el-button>
          </template>
        </el-dialog>
      </el-tab-pane>



      <!-- 출금 설정 -->
      <el-tab-pane label="출금 설정" name="settings">
        <div class="toolbar">
          <el-button type="primary" @click="saveSettings">저장</el-button>
          <el-button :icon="Refresh" @click="loadSettings">새로고침</el-button>
        </div>
        <el-form :model="settings" label-width="120px" style="max-width: 640px">
          <el-form-item label="환율(포인트당)">
            <el-input
              v-model="settings.rate"
              type="number"
              step="0.01"
              min="0"
              placeholder="환율을 입력하세요, 예: 0.01"
            />
          </el-form-item>
          <el-form-item label="플랫폼 수수료(%)">
            <el-input
              v-model="settings.feePercent"
              type="number"
              step="0.1"
              min="0"
              max="100"
              placeholder="백분율을 입력하세요, 예: 10"
            />

          </el-form-item>
          <el-form-item label="최소 포인트">
            <el-input
              v-model="settings.minPoints"
              type="number"
              step="1"
              min="0"
              placeholder="최소 포인트를 입력하세요"
            />
          </el-form-item>
          <el-form-item label="은행 목록(쉼표 구분)">
            <el-input
              v-model="settings.banks as any"
              placeholder="예: 공상은행,건설은행,농업은행"
            />
            <div style="color: #aaa; font-size: 12px; margin-top: 6px">
              참고: 여기서는 쉼표로 구분된 문자열로 단순화하며, 저장 시 배열로 분할됩니다
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 충전 심사 -->
      <el-tab-pane label="충전 심사" name="recharge">
        <div class="toolbar">
          <el-button :icon="Refresh" @click="fetchRecharges('pending')">대기 중 새로고침</el-button>
        </div>
        <el-table :data="rechargeList" v-loading="rechargeLoading" stripe>
          <el-table-column prop="id" label="충전 ID" width="80" />
          <el-table-column label="사용자" width="150">
            <template #default="{ row }">
              <div>{{ row.user?.loginId || '알 수 없음' }}</div>
              <div style="font-size: 12px; color: #666;">{{ row.user?.name || row.user?.nickname || '' }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="pointsCredited" label="포인트" width="120" />
          <el-table-column prop="referenceNo" label="참조 번호" min-width="160" />
          <el-table-column prop="purchaserName" label="구매자" width="140" />
          <el-table-column prop="purchaserPhone" label="전화번호" width="160" />
          <el-table-column prop="status" label="상태" width="100" />
          <el-table-column label="작업" width="180" align="center">
            <template #default="{ row }">
              <el-button type="success" :icon="Check" size="small" @click="approveRecharge(row)"
                >승인</el-button
              >
              <el-button type="danger" :icon="Close" size="small" @click="rejectRecharge(row)"
                >거부</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>


    </el-tabs>
  </div>
</template>

<style scoped>
.payment-mgmt {
  padding: 16px;
}
.title {
  margin: 0 0 12px;
}
.toolbar {
  display: flex;
  gap: 8px;
  margin: 10px 0;
  align-items: center;
}
.processed-status {
  color: #909399;
  font-size: 12px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
}
</style>
